package com.zhbcm.socket.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/4/22 21:33
 */
public class TalkClient
{
    public static void main(String[] args)
    {
        try
        {
            Socket socket = new Socket("127.0.0.1", 4700);
            // 由系统标准输入设备构造BufferedReader对象
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            // 由Socket对象得到输出流，并构造PrintWriter对象
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            // 由Socket对象得到输入流，并构造相应的BufferedReader对象
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 从系统标准输入读入一字符串
            String readline = br.readLine();
            while (!readline.equals("bye"))
            {
                // 将从系统标准输入读入的字符串输出到Server
                pw.println(readline);
                // 刷新输出流，使Server发上收到该字符串
                pw.flush();
                // 在系统标准输出上打印读入的字符串
                System.out.println("Client say:" + readline);
                // 从Server读入一字符串，并打印到标准输出上
                System.out.println("Server say:" + is.readLine());
                // 从系统标准输入读入一字符串
                readline = br.readLine();
                // 关闭Socket输出流
                pw.close();
                // 关闭Socket输入流
                is.close();
                // 关闭Socket
                socket.close();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
